﻿#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using PHMEE.EntityFrameworkCore;

namespace PHMEE.EnergyEfficiency;

public class VesselEeConfigRepository : IVesselEeConfigRepository
{
    private readonly PHMEEDbContext _context;

    public VesselEeConfigRepository(PHMEEDbContext context)
    {
        _context = context;
    }

    public Task<List<VesselEeConfig>> GetByFleetIdAsync(Guid fleetId)
    {
        return _context.VesselEeConfigs
            .Where(v => v.FleetId == fleetId)
            .ToListAsync();
    }

    public async Task<VesselEeConfig?> GetByIdAsync(Guid id)
    {
        return await _context.VesselEeConfigs.FindAsync(id);
    }

    public Task<VesselEeConfig?> GetByVesselIdAsync(Guid vesselId)
    {
        // TODO: VesselId 与 ID 合并了，不再需要这个方法，待迁移完成后删除
        return GetByIdAsync(vesselId);
    }

    public Task<List<VesselEeConfig>> GetAllAsync()
    {
        return _context.VesselEeConfigs.ToListAsync();
    }

    public async Task InsertAsync(VesselEeConfig vesselEeConfig)
    {
        ArgumentNullException.ThrowIfNull(vesselEeConfig);

        await _context.VesselEeConfigs.AddAsync(vesselEeConfig);
        await _context.SaveChangesAsync();
    }

    public async Task UpdateAsync(VesselEeConfig vesselEeConfig)
    {
        ArgumentNullException.ThrowIfNull(vesselEeConfig);

        _context.VesselEeConfigs.Update(vesselEeConfig);
        await _context.SaveChangesAsync();
    }

    public async Task DeleteAsync(Guid id)
    {
        var config = await _context.VesselEeConfigs.FindAsync(id);
        if (config != null)
        {
            _context.VesselEeConfigs.Remove(config);
            await _context.SaveChangesAsync();
        }
    }
}